a <- sample(c(1, 2), 1)
b <- sample(c(2, 4), 1)3 Further Exercises
Exercise 1
The code below creates the vectors a and b. a randomly takes the value 1 or 2 and b randomly takes the value 2 or 4 (this is done using the sample() function which you can learn more about using the help() function).
Create a new vector c which is:
TRUEif bothaandbare equal.FALSEifaandbare different.
Create another vector d, which uses a single logical operator to compare a and b, and returns the value:
FALSEwhenais 1 andbis 2.TRUEwhenais 2 andbis 2.FALSEwhenais 1 andbis 4.FALSEwhenais 2 andbis 4.
Exercise 2
\[ \boldsymbol{P}=\begin{bmatrix}3\\54\\1\\6\\0\end{bmatrix},\,\,\,\,\,\,\,\,\, \boldsymbol{Q}=\begin{bmatrix}18\\-1\end{bmatrix} \]
Create the vectors \(\boldsymbol{P}\) and \(\boldsymbol{Q}\) in R.
Write code to complete the calculation \(\boldsymbol{P}+2\times\boldsymbol{Q}\) and save the result as a new vector called R.
Extract the 2nd and 5th elements of R. Can you predict what these values will be before running your code?
Exercise 3
Create the sequence TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE using the rep() function and save the result as a vector called logical. Change logical to a numeric vector called numeric.
Next, create the vector \(\begin{bmatrix}5.50,5.25,5.00,4.75,4.50,4.25,4.00,3.75,3.50\end{bmatrix}^\intercal\) using the seq() function and call it sequence.
Finally add together numeric and sequence and use the subset() function to keep only the elements which are greater than 5.50.